<?php
namespace App\Service\Member;

use Illuminate\Support\Facades\DB;

class PayService extends BaseService
{
    //支付

    //通过token获取医护信息
    public function userByToken($token)
    {
        $log = (array) $this->dbConn($this->dbUlogin)
            ->where('token', $token)
            ->orderBy('id', 'desc')
            ->first();
        if (empty($log)) {
            return $this->toback(-2, '没有登录');
        }
        $res = (array) $this->dbConn($this->dbUser)
            ->where('id', $log['uid'])
            ->first();
        return empty($res) ? [] : $res;
    }

    /**
     * 创建订单
     * 获取订单信息
     * @param int $type
     * @param int $id
     * @param int $uid
     */
    public function wxPayAdd($type, $id, $uid,$pay_way)
    {
        $orderno = toOrder();
        if ($type == 1) {
            //患者咨询医生开启对话uds_patient
            $duihua = (array) $this->dbConn($this->dbUdsPatient)
                ->where('id', $id)
                ->first(); //对话窗口
            if (empty($duihua)) {
                return $this->toback(-2, '没有对话');
            }
            if ($duihua['is_pay'] == 2) {
                return $this->toback(-2, '对话已支付');
            }
            $dOne = (array) $this->dbConn($this->dbDoctor)
                ->where('del', 0)
                ->where('id', $duihua['doctor_id'])
                ->first(); //价目配置
            if (empty($dOne)) {
                return $this->toback(-2, '没有医生');
            }
            $price = $dOne['price'];
            $tname = 'talk-client';
        } else if ($type == 2) {
            //患者查看医生帖子tieba
            $tieba = (array) $this->dbConn($this->dbTieba)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($tieba)) {
                return $this->toback(-2, '没有记录');
            }
            if (!$tieba['read_cost']) {
                return $this->toback(-2, '该文章是免费的');
            }
            $tbUser = (array) $this->dbConn($this->dbTbPay)
                ->where('tiezi', $id)
                ->where('uid', $uid)
                ->first();
            if (!empty($tbUser) && $tbUser['is_pay'] == 2) {
                return $this->toback(-2, '已支付');
            }
            $tuid = $this->dbConn($this->dbTbPay)->insertGetId([
                'tiezi' => $id, 'uid' => $uid, 'addtime' => toDate(),
                'read_cost' => $tieba['read_cost'],
            ]);
            if (!$tuid) {
                return $this->toback(-1, '阅读失败');
            }
            $price = $tieba['read_cost'];
            $tname = 'read-cost';
        } else if ($type == 3) {
            //患者发布代办预约订单gc_daiban
            $daiban = (array) $this->dbConn($this->dbDaiban)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($daiban)) {
                return $this->toback(-2, '没有记录');
            }
            if ($daiban['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $daiban['price'];
            $tname = 'daiban';
        } else if ($type == 4) {
            //患者发布小区医护预约订单gc_yihu
            $yihu = (array) $this->dbConn($this->dbYihu)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($yihu)) {
                return $this->toback(-2, '没有记录');
            }
            if ($yihu['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $yihu['price'];
            $tname = 'xiaoqu-yuyue';
        } else if ($type == 5) {
            //患者发布陪诊预约订单gc_peizhen
            $yihu = (array) $this->dbConn($this->dbPeizhen)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($yihu)) {
                return $this->toback(-2, '没有记录');
            }
            if ($yihu['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $yihu['price'];
            $tname = 'peizhen';
        } else if ($type == 6) {
            //药品订单drug_order
            $doOne = (array) $this->dbConn($this->dbDrugOrder)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($doOne)) {
                return $this->toback(-2, '没有记录');
            }
            if ($doOne['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $doOne['price'];
            $tname = 'yaopin-order';
        } else {
            return $this->toback(-2, '业务类型错误');
        }
        $oData = [
            'uid' => $uid, 'yw_type' => $type, 'yw_id' => $id,
            'pay_way' => $pay_way, 'out_trade_no' => $orderno
        ];
        $lastid = $this->dbConn($this->dbPay)->insertGetId($oData);
        if (!$lastid) {
            return $this->toback(-1, '订单失败');
        }
        $ary = [
            'payid' => $lastid,
            'orderno' => $orderno,
            'price' => $price,
            'tname' => $tname,
        ];
        return $this->toback(0, '', $ary);
    }

    //更新
    public function wxPayModify($id, $pas)
    {
        $pas['uptime'] = toDate();
        return $this->dbConn($this->dbPay)->where('id', $id)
            ->update($pas);
    }

    //微信通知
    public function wxNotice($ndata,$pay_way=1)
    {
        $wxjson = [
            'pay_way' => $pay_way,
            'otherjson' => json_encode($ndata, JSON_UNESCAPED_UNICODE),
            'addtime' => toDate(),
        ];
        return $this->dbConn($this->dbPnotice)->insertGetId($wxjson);
    }

    //微信成功更新
    public function wxNoticeModify($id, $out_trade_no)
    {
        $payOne = (array) $this->dbConn($this->dbPay)
            ->where('out_trade_no', $out_trade_no)
            ->first();
        if (empty($payOne)) {
            return $this->toback(-2, '没有支付记录');
        }
        DB::beginTransaction(); //开启事务
        try {
            //更新通知
            $this->dbConn($this->dbPnotice)->where('id', $id)
                ->update(['out_trade_no' => $out_trade_no]);
            //更新支付状态
            $this->dbConn($this->dbPay)->where('out_trade_no', $out_trade_no)
                ->update(['status' => 2, 'uptime' => toDate()]);
            if ($payOne['yw_type'] == 1) {
                $this->dbConn($this->dbUdsPatient)->where('id', $payOne['yw_id'])
                    ->update(['is_pay' => 2, 'paytime' => toDate()]);
            } else if ($payOne['yw_type'] == 2) {
                $this->dbConn($this->dbTbPay)
                    ->where('id', $payOne['yw_id'])
                    ->update(['is_pay' => 2, 'paytime' => toDate()]);
            } else if ($payOne['yw_type'] == 3) {
                $this->dbConn($this->dbDaiban)
                    ->where('id', $payOne['yw_id'])
                    ->update(['status' => 2, 'paytime' => toDate()]);
            } else if ($payOne['yw_type'] == 4) {
                $this->dbConn($this->dbYihu)
                    ->where('id', $payOne['yw_id'])
                    ->update(['status' => 2, 'paytime' => toDate()]);
            } else if ($payOne['yw_type'] == 5) {
                $this->dbConn($this->dbPeizhen)
                    ->where('id', $payOne['yw_id'])
                    ->update(['status' => 2, 'paytime' => toDate()]);
            } else if ($payOne['yw_type'] == 6) {
                $this->dbConn($this->dbDrugOrder)
                    ->where('id', $payOne['yw_id'])
                    ->update(['status' => 2, 'paytime' => toDate()]);
            }
            //更新订单状态
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code'=>-1, 'msg'=>'操作失败');
        }
    }

    /**
     * 余额支付
     */
    public function yuPay($type, $id, $uOne)
    {
        if ($type == 1) {
            //患者咨询医生开启对话uds_patient
            $duihua = (array) $this->dbConn($this->dbUdsPatient)
                ->where('id', $id)
                ->first(); //对话窗口
            if (empty($duihua)) {
                return $this->toback(-2, '没有对话');
            }
            if ($duihua['is_pay'] == 2) {
                return $this->toback(-2, '对话已支付');
            }
            $dOne = (array) $this->dbConn($this->dbDoctor)
                ->where('del', 0)
                ->where('id', $duihua['doctor_id'])
                ->first(); //价目配置
            if (empty($dOne)) {
                return $this->toback(-2, '没有医生');
            }
            $price = $dOne['price'];
        } else if ($type == 2) {
            //患者查看医生帖子tieba
            $tieba = (array) $this->dbConn($this->dbTieba)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($tieba)) {
                return $this->toback(-2, '没有记录');
            }
            if (!$tieba['read_cost']) {
                return $this->toback(-2, '该文章是免费的');
            }
            $tbUser = (array) $this->dbConn($this->dbTbPay)
                ->where('tiezi', $id)
                ->where('uid', $uOne['id'])
                ->first();
            if (!empty($tbUser) && $tbUser['is_pay'] == 2) {
                return $this->toback(-2, '已支付');
            }
            $tuid = $this->dbConn($this->dbTbPay)->insertGetId([
                'tiezi' => $id, 'uid' => $uOne['id'], 'addtime' => toDate(),
                'read_cost' => $tieba['read_cost'],
            ]);
            if (!$tuid) {
                return $this->toback(-1, '阅读失败');
            }
            $price = $tieba['read_cost'];
        } else if ($type == 3) {
            //患者发布代办预约订单gc_daiban
            $daiban = (array) $this->dbConn($this->dbDaiban)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($daiban)) {
                return $this->toback(-2, '没有记录');
            }
            if ($daiban['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $daiban['price'];
        } else if ($type == 4) {
            //患者发布小区医护预约订单gc_yihu
            $yihu = (array) $this->dbConn($this->dbYihu)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($yihu)) {
                return $this->toback(-2, '没有记录');
            }
            if ($yihu['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $yihu['price'];
        } else if ($type == 5) {
            //患者发布陪诊预约订单gc_peizhen
            $yihu = (array) $this->dbConn($this->dbPeizhen)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($yihu)) {
                return $this->toback(-2, '没有记录');
            }
            if ($yihu['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $yihu['price'];
        } else if ($type == 6) {
            //药品订单drug_order
            $doOne = (array) $this->dbConn($this->dbDrugOrder)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($doOne)) {
                return $this->toback(-2, '没有记录');
            }
            if ($doOne['status'] > 1) {
                return $this->toback(-2, '已支付');
            }
            $price = $doOne['price'];
        } else {
            return $this->toback(-2, '类型错误');
        }
        if ($price > $uOne['balance']) {
            return $this->toback(-2, '余额不足');
        }
        DB::beginTransaction(); //开启事务
        try {
            //添加支付记录
            $this->dbConn($this->dbPay)->insertGetId([
                'uid' => $uOne['id'], 'yw_type' => 6, 'yw_id' => $id,
                'pay_way' => 3, 'out_trade_no' => toOrder(), 'money' => $price,
                'status' => 2, 'addtime' => toDate(),
            ]);
            //减余额
            $this->dbConn($this->dbUser)->where('id', $uOne['id'])
                ->update(['balance' => $uOne['balance'] - $price]);
            //更新业务状态
            if ($type == 1) {
                $this->dbConn($this->dbUdsPatient)
                    ->where('id', $id)
                    ->update(['is_pay' => 2, 'paytime' => toDate()]);
            } else if ($type == 2) {
                $this->dbConn($this->dbTbPay)
                    ->where('tiezi', $id)
                    ->where('uid', $uOne['id'])
                    ->update(['is_pay' => 2, 'paytime' => toDate()]);
            } else if ($type == 3) {
                $this->dbConn($this->dbDaiban)
                    ->where('id', $id)
                    ->update(['status' => 2, 'paytime' => toDate()]);
            } else if ($type == 4) {
                $this->dbConn($this->dbYihu)
                    ->where('id', $id)
                    ->update(['status' => 2, 'paytime' => toDate()]);
            } else if ($type == 5) {
                $this->dbConn($this->dbPeizhen)
                    ->where('id', $id)
                    ->update(['status' => 2, 'paytime' => toDate()]);
            } else if ($type == 6) {
                $this->dbConn($this->dbDrugOrder)
                    ->where('id', $id)
                    ->update(['status' => 2, 'paytime' => toDate()]);
            }
            //更新订单状态
            DB::commit(); //提交事务
            return $this->toback();
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return $this->toback(-1, 'error');
        }
    }
}
